package tiled.simple.gwt.client;

import java.util.ArrayList;
import java.util.Iterator;

import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.Contact;

public class GameContactListener implements ContactListener{

	public ArrayList<Contact> points = new ArrayList<Contact>();	
	
	public void beginContact(Contact point) {
		points.add(point);
	}

	public void endContact(Contact point) {
		points.remove(point);
	}

	public void preSolve(Contact contact, Manifold oldManifold) {
	}

	public void postSolve(Contact contact, ContactImpulse impulse) {
	}

	public boolean isHeroOnTheFloor(){//Context2d context){
		boolean r=false;
		
		Iterator<Contact> itr = points.iterator();
		while(itr.hasNext()){
			Contact point = itr.next();
			if(CheckPoint(point,"Hero","Floor")){

				Vec2 v=point.getManifold().localPoint;
				
				/*
				Body b1=point.getFixtureA().getBody();
				Body b2=point.getFixtureB().getBody();
				
				Vec2 vA;
				Vec2 vB;
				if(b1.getUserData().equals("Hero")){
					vA=b1.getPosition();
					vB=b2.getPosition();
				}else{
					vA=b2.getPosition();
					vB=b1.getPosition();
				}*/
				

				/*
				CssColor c = CssColor.make("rgba(255,255,255, 255)");
		        context.setFillStyle(c);
		        context.fillText("v.x="+v.x,100,200);
		        context.fillText("v.y="+v.y,100,220);
		        context.fillText("A",vA.x*Game.PIXEL_PER_METER,vA.y*Game.PIXEL_PER_METER);
		        context.fillText("B",vB.x*Game.PIXEL_PER_METER,vB.y*Game.PIXEL_PER_METER);
		        context.fillText("o",(v.x+vB.x)*Game.PIXEL_PER_METER,(v.y+vB.y)*Game.PIXEL_PER_METER);
		        context.fill();
		        */
		        if(v.y<0) {r=true;}

			}

			
			


			
		}
		return r;
	}
	
	private boolean CheckPoint(Contact point,String name1,String name2){
		Body b1=point.getFixtureA().getBody();
		Body b2=point.getFixtureB().getBody();

		boolean flag=false;
		if((b1.getUserData().equals(name1) && b2.getUserData().equals(name2))||
		   (b1.getUserData().equals(name2) && b2.getUserData().equals(name1))){
			flag=true;
		}
		return flag;
	}

}
